const fs = require('fs');
const path = require('path');

// A simple implementation of Rollup

function bundle(entry, output) {
    const modules = {};

    function readModule(filePath) {
        const code = fs.readFileSync(filePath, 'utf-8');
        const module = { code, dependencies: [] };
        const dir = path.dirname(filePath);

        // Find dependencies (naive implementation for `import` statements)
        module.code = module.code.replace(/import\s+.*?\s+from\s+['"](.*?)['"]/g, (match, depPath) => {
            const absPath = path.resolve(dir, depPath);
            module.dependencies.push(absPath);
            return `// ${match}`;
        });

        modules[filePath] = module;

        // Recursively read dependencies
        module.dependencies.forEach(dep => {
            if (!modules[dep]) {
                readModule(dep);
            }
        });
    }

    readModule(entry);

    // Bundle all modules into a single file
    let bundledCode = '';
    Object.keys(modules).forEach(filePath => {
        bundledCode += `// Module: ${filePath}\n`;
        bundledCode += modules[filePath].code + '\n\n';
    });

    fs.writeFileSync(output, bundledCode);
    console.log(`Bundled to ${output}`);
}

// Example usage
const entryFile = path.resolve(__dirname, './src/index.js');
const outputFile = path.resolve(__dirname, './dist/bundle.js');
bundle(entryFile, outputFile);